import requests
import logging
from src.config import LoggerConfig, Config
from src.spider.sinong_login import SinongLogin

# 配置日志
LoggerConfig.configure_logger('log/sn-audit-report.log')

class PDFUploader:
    def __init__(self, pdf_path, upload_url, cookies, data):
        self.pdf_path = pdf_path
        self.upload_url = upload_url
        self.headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Origin': 'https://i-dev.sinongcpa.cn',
            'Pragma': 'no-cache',
            'Referer': 'https://i-dev.sinongcpa.cn/f-cpscm/',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
            'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
        }
        self.cookies = cookies
        self.data = data
        self.binary_data = None
        self.logging = logging.getLogger('PDFUploader')

    def pdf_to_binary(self):
        """将PDF文件转换为二进制数据"""
        try:
            with open(self.pdf_path, 'rb') as pdf_file:
                self.binary_data = pdf_file.read()
            self.logging.info(f"PDF文件读取成功: {self.pdf_path}")
        except Exception as e:
            self.logging.error(f"读取PDF文件时发生错误: {e}")
            raise

    def auto_login(self):
        """重新登录获取新的Cookie"""
        # 在这里实现自动登录逻辑，并返回新的Cookie
        new_cookie = ""
        # logging.info("自动登录成功，获取到新的Cookie")
        return new_cookie

    def upload_pdf(self, retry=False):
        """上传PDF文件"""
        if self.binary_data is None:
            self.logging.error("二进制数据为空，无法上传PDF文件")
            return

        files = {
            'File': (self.pdf_path.split('\\')[-1], self.binary_data, 'application/pdf')
        }

        try:
            response = requests.post(url=self.upload_url, headers=self.headers, cookies= self.cookies, data = self.data, files=files)
            self.logging.info(f"上传请求状态码: {response.status_code}")

            if response.status_code != 200:
                self.logging.warning(f"状态码 {response.status_code} 不为200，准备重新登录并重试")
                if not retry:
                    sinong = SinongLogin()
                    self.headers['Cookie'] = sinong.run()
                    self.upload_pdf(retry=True)
                else:
                    self.logging.error(f"重试后仍然失败，状态码: {response.status_code}")
            else:
                self.logging.debug(f"响应内容: {response.text}")
        except Exception as e:
            self.logging.error(f"上传PDF文件时发生错误: {e}")
            raise

if __name__ == '__main__':
    pdf_path = 'D:\\Python_files\\司农实习文件\\Code\\sn-audit-report\\src\\spider\\directory\\P2300919014_ro2.pdf'
    upload_url = 'https://i-dev.sinongcpa.cn/cpscm/C22/Sign'
    cookies = {
        '.ASPXAUTH': 'F08DBA88E7F818175B89DAB7AE937B161DF823F5AE4122B5951C3B5F51A5EF6F17D3AC369B413D8D0349909DF470E6DDD8FE1049D8A0AAA2A5E264C41621069F1B214A962BA17E9D536AFE289BE4E1ED142449CCF93E5B6547F08D7D82F8C915335D3A46721843FFA8D0395DB86D6A478312379538B55B9695524B06F0B84C07A24B17B4E700D4357C48261E4394050144BDC9277865C802A1DD14FE87D7D05F7F6B35EA5E7D658A6B725057F94FA81630A2FEE2E3B4F4D11E838B10FBEC06EB9ED34E3B5E950A250E183D8FF7C7FAF017186527BF07803A108BC198B532EC1EC4F85A8B5A0AE12D7B234295FFD2D9022F718AEA9DC173BD5BDF0947589690D33715151DA6F48716D4D1934F56D26A7A95823DAB1F5DB1F01AB98612F3A247468ABD3DFDF27E8032E77117F395DBC294',
        'ASP.NET_SessionId': 'dnaixqr3i3xenta0ecjik0hq',
    }
    data = {
        'Id': '73442',
        'sObj': '注册会计师行业统一监管平台',
        'sRNumber': '报表歪',
        'Flag': 'false'
    }

    uploader = PDFUploader(pdf_path, upload_url, cookies, data)
    try:
        uploader.pdf_to_binary()
        uploader.upload_pdf()
    except Exception as e:
        print(f"程序运行过程中发生错误: {e}")
